const express = require('express');
const router = express.Router();
const fs = require('fs');
const { multerM } = require('../../model/tools.js')
const ArticleCateModel = require('../../model/articleCate.js')
const ArticleModel = require('../../model/article.js')
router.get('/', async (req, res) => {
    let page = req.query.page || 1;
    let pagesize = 3;
    //    let result = await ArticleModel.find({}).skip((page-1)*pagesize).limit(pagesize)
    let result = await ArticleModel.aggregate([
        {
            $lookup: {
                from: "article_cate",
                localField: 'cid',
                foreignField: '_id',
                as: 'cate'
            }
        }, {
            $sort: { add_time: -1 }
        }, {
            $skip: (page - 1) * pagesize
        }, {
            $limit: pagesize
        }
    ])
    let count = await ArticleModel.count({});
    res.render('admin/article/index', {
        list: result,
        totalPages: Math.ceil(count / pagesize),
        currentPage: page
    })
})
router.get('/add', async (req, res) => {
    let cateResult = await ArticleCateModel.aggregate([
        {
            $lookup: {
                from: "article_cate",
                localField: '_id',
                foreignField: 'pid',
                as: 'items'
            }
        }, {
            $match: {
                pid: "0"
            }
        }
    ])
    res.render('admin/article/add', { catelist: cateResult })
})
router.post('/doadd', multerM().single('article_img'), async (req, res) => {
    let article_img = req.file ? req.file.path.substr(6) : '';
    let result = new ArticleModel(Object.assign(req.body, { article_img, add_time: Date.now() }))
    await result.save();
    res.redirect('/admin/article')
})
router.get('/edit', async (req, res) => {
    let id = req.query.id;
    let cateResult = await ArticleCateModel.aggregate([
        {
            $lookup: {
                from: "article_cate",
                localField: '_id',
                foreignField: 'pid',
                as: 'items'
            }
        }, {
            $match: {
                pid: "0"
            }
        }
    ])
    let ArResult = await ArticleModel.find({ _id: id })
    // console.log(ArResult[0].content)
    // console.log('1')
    res.render('admin/article/edit', {
        catelist: cateResult,
        articlelist: ArResult[0]
    })
})
router.post('/doEdit', multerM().single('article_img'), async (req, res) => {
    let id = req.body.id;
    if (req.file) {
        let article_img = req.file ? req.file.path.substr(6) : '';
        await ArticleModel.updateOne({ _id: id }, Object.assign(req.body, { article_img, add_time: Date.now() }))
    } else {
        await ArticleModel.updateOne({ _id: id }, Object.assign(req.body, { add_time: Date.now() }))

    }
    res.redirect('/admin/article')
})
router.get('/delete', async (req, res) => {
    let id = req.query.id;
    let resultList = await ArticleModel.find({ _id: id });
    let delResult = await ArticleModel.deleteOne({ _id: id })

    let ishas = /<img\ssrc=.*>/.test(resultList[0].content);

    //    console.log(b)
    // console.log(b)
    if (delResult.deletedCount == 1) {
        if (resultList[0].article_img) {
            fs.unlink('static/' + resultList[0].article_img, (err) => {
                // console.log(err)
            })
        }
        if (resultList[0].content) {
            if (ishas) {
                let a = resultList[0].content.indexOf('upload');
                let b = resultList[0].content.substr(a, 31)
                fs.unlink('static/' + b, (err) => {
                    // console.log(err)
                })

            }
        }
    }
    res.redirect('/admin/article')
})
router.post('/doUploadImage', multerM().single('file'), (req, res) => {
    let imgsrc = req.file ? req.file.path.substr(6) : '';
    res.send(
        { link: imgsrc }
    )
})
module.exports = router;